﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Controls;
using System.ComponentModel;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Unity;
using Interfaces;

namespace ViewModels
{
    public class NewsViewModel : BindableBase, INewsViewModel
    {
        public INewsModel NewsModel { get { return _newsModel; } private set { SetProperty(ref _newsModel, value); } }
        public ICommand SearchCommand { get { return _searchCommand == null ? _searchCommand = new DelegateCommand<string>(OnSearch) : _searchCommand; } }

        private ICommand _searchCommand;
        private readonly ILoggerFacade _logger;
        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAgregator;
        private INewsModel _newsModel;

        public NewsViewModel(ILoggerFacade logger, IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAgregator, INewsModel newsModel)
        {
            _logger = logger;
            _container = container;
            _regionManager = regionManager;
            _eventAgregator = eventAgregator;
            _newsModel = newsModel;

            _eventAgregator.GetEvent<ChartResfreshEvent>().Subscribe(OnSearch);
        }

        private void OnSearch(string keyword)
        {
            try
            {
                _newsModel.GetService(keyword);
            }
            catch (Exception e)
            {
                _logger.Log(e.Message, Category.Exception, Priority.High);
            }
        }
    }
}
